package com.TTBook.Filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

/**
 * WEB 页面字符地滤器
 * 
 * @author Fountain Chan
 * @version 1.0.0
 */
public class EncodingFilter extends HttpServlet implements Filter {
	
	private static final long serialVersionUID = 2808940496129346400L;

	private FilterConfig filterConfig;

	private String targetEncoding = "UTF-8";
	
	private final static String DEFAULT_ENCODING = "UTF-8";

	public void init(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
		targetEncoding = this.filterConfig.getInitParameter("encoding");
		if(null == targetEncoding || targetEncoding.trim().length() <= 0) {
			targetEncoding = DEFAULT_ENCODING;
		} else {
			targetEncoding = targetEncoding.trim();
			System.out.println(" ========================== EcodingFilter ========================== ");
			System.out.println("  -  Current encoding is: '" + targetEncoding + "'");
			System.out.println(" =================================================================== ");
		}
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) {
		try {
			request.setCharacterEncoding(targetEncoding);
			filterChain.doFilter(request, response);
		} catch (ServletException sx) {
			filterConfig.getServletContext().log(sx.getMessage());
		} catch (IOException iox) {
			filterConfig.getServletContext().log(iox.getMessage());
		}
	}

	public void destroy() {
		filterConfig = null;
		targetEncoding = null;
	}
}
